using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Net;
using System.Threading;
using System.IO;


using System.ComponentModel;
using System.Data;
using System.IO.Ports;
namespace primeraDescarga
{
    class Program
    {
        static void Main(string[] args)
        {
            while (1 > 0)
            {
                try
                {
                    Console.WriteLine("Favor no cerrar la venta,Proceso Activity Technology");
                    conexionSQL db = new conexionSQL("Data Source=SERVER\\SQLEXPRESS;Initial Catalog=EnterpriseAdminDb;Integrated Security=True");
                    
                    //Genera VENDEDORES
                    db.Consulta("SELECT [Descrip],[CodVend],[Direc1],[Telef],[Movil] FROM [EnterpriseAdminDb].[dbo].[SAVEND]");
                    String file_pathMTprecio = "D:/ProcesosActivity/XML/Vendedores.xml";
                    XmlTextWriter writerMTprecio;
                    writerMTprecio = new XmlTextWriter(file_pathMTprecio, Encoding.UTF8);
                    writerMTprecio.Formatting = Formatting.Indented;
                    writerMTprecio.WriteStartDocument();
                    writerMTprecio.WriteStartElement("vendedores");
                    while (db.Dr.Read())
                    {
                        writerMTprecio.WriteStartElement("registro");
                        writerMTprecio.WriteElementString("Descrip", db.Dr["Descrip"].ToString());
                        writerMTprecio.WriteElementString("CodVend", db.Dr["CodVend"].ToString());
                        writerMTprecio.WriteElementString("Direc1", db.Dr["Direc1"].ToString());
                        writerMTprecio.WriteElementString("Telef", db.Dr["Telef"].ToString());
                        writerMTprecio.WriteElementString("Movil", db.Dr["Movil"].ToString());
                        writerMTprecio.WriteEndElement();
                    }
                    writerMTprecio.WriteEndElement();
                    writerMTprecio.WriteEndDocument();
                    writerMTprecio.Flush();
                    writerMTprecio.Close();


                    //Genera CLIENTES
                    db.Consulta("SELECT [CodClie],[Descrip],[Represent],[Direc1],[Direc2],[Telef],[Descto],[LimiteCred]" +
                        ",[Activo],[ID3],[EsCredito],[DiasCred] FROM [EnterpriseAdminDb].[dbo].[SACLIE]");
                    String file_pathMVprecio = "D:/ProcesosActivity/XML/Clientes.xml";
                    XmlTextWriter writerMVprecio;
                    writerMVprecio = new XmlTextWriter(file_pathMVprecio, Encoding.UTF8);
                    writerMVprecio.Formatting = Formatting.Indented;
                    writerMVprecio.WriteStartDocument();
                    writerMVprecio.WriteStartElement("clientes");
                    while (db.Dr.Read())
                    {
                        writerMVprecio.WriteStartElement("registro");
                        writerMVprecio.WriteElementString("CodClie", db.Dr["CodClie"].ToString());
                        writerMVprecio.WriteElementString("Descrip", db.Dr["Descrip"].ToString());
                        writerMVprecio.WriteElementString("Represent", db.Dr["Represent"].ToString());
                        writerMVprecio.WriteElementString("Direc1", db.Dr["Direc1"].ToString());
                        writerMVprecio.WriteElementString("Direc2", db.Dr["Direc2"].ToString());
                        writerMVprecio.WriteElementString("Telef", db.Dr["Telef"].ToString());
                        writerMVprecio.WriteElementString("Descto", db.Dr["Descto"].ToString());
                        writerMVprecio.WriteElementString("LimiteCred", db.Dr["LimiteCred"].ToString());
                        writerMVprecio.WriteElementString("Activo", db.Dr["Activo"].ToString());
                        writerMVprecio.WriteElementString("ID3", db.Dr["ID3"].ToString());
                        writerMVprecio.WriteElementString("EsCredito", db.Dr["EsCredito"].ToString());
                        writerMVprecio.WriteElementString("DiasCred", db.Dr["DiasCred"].ToString());
                        writerMVprecio.WriteEndElement();
                    }
                    writerMVprecio.WriteEndElement();
                    writerMVprecio.WriteEndDocument();
                    writerMVprecio.Flush();
                    writerMVprecio.Close();


                    //Genera PRODUCTOS
                    db.Consulta("SELECT [CodProd],[Descrip],[Unidad],[Precio1],[Activo],[CostPro] FROM [EnterpriseAdminDb].[dbo].[SAPROD]");
                    String file_pathVenden = "D:/ProcesosActivity/XML/Productos.xml";
                    XmlTextWriter writerVenden;
                    writerVenden = new XmlTextWriter(file_pathVenden, Encoding.UTF8);
                    writerVenden.Formatting = Formatting.Indented;
                    writerVenden.WriteStartDocument();
                    writerVenden.WriteStartElement("productos");
                    while (db.Dr.Read())
                    {
                        writerVenden.WriteStartElement("registro");
                        writerVenden.WriteElementString("CodProd", db.Dr["CodProd"].ToString());
                        writerVenden.WriteElementString("Descrip", db.Dr["Descrip"].ToString());
                        writerVenden.WriteElementString("Unidad", db.Dr["Unidad"].ToString());
                        writerVenden.WriteElementString("Precio1", db.Dr["Precio1"].ToString());
                        writerVenden.WriteElementString("Activo", db.Dr["Activo"].ToString());
                        writerVenden.WriteElementString("CostPro", db.Dr["CostPro"].ToString());
                        writerVenden.WriteEndElement();
                    }
                    writerVenden.WriteEndElement();
                    writerVenden.WriteEndDocument();
                    writerVenden.Flush();
                    writerVenden.Close();

                    db.Cnn.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }


                //Sube VENDEDORES
                try
                {
                    FtpWebRequest requestMtPrecio = (FtpWebRequest)FtpWebRequest.Create("ftp://activitycolombia.com/mainwebsite_html/ventas/Procesos/Xmls/Vendedores.xml");
                    requestMtPrecio.Method = WebRequestMethods.Ftp.UploadFile;
                    requestMtPrecio.Credentials = new NetworkCredential("activitymedellin@activitycolombia.com", "ts34Ng45Y64");
                    requestMtPrecio.UsePassive = false;
                    requestMtPrecio.UseBinary = true;
                    requestMtPrecio.KeepAlive = true;
                    // Defino el path del archivo
                    FileStream streamMtPrecio = File.OpenRead("D:\\ProcesosActivity\\XML\\Vendedores.xml");
                    byte[] bufferMtPrecio = new byte[streamMtPrecio.Length];
                    streamMtPrecio.Read(bufferMtPrecio, 0, bufferMtPrecio.Length);
                    streamMtPrecio.Close();
                    Stream reqStreamMtPrecio = requestMtPrecio.GetRequestStream();
                    reqStreamMtPrecio.Write(bufferMtPrecio, 0, bufferMtPrecio.Length);
                    reqStreamMtPrecio.Flush();
                    reqStreamMtPrecio.Close();
                    Console.WriteLine("llego el xml Vendedores");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                //Sube CLIENTES
                try
                {
                    FtpWebRequest requestMtPrecio = (FtpWebRequest)FtpWebRequest.Create("ftp://activitycolombia.com/mainwebsite_html/ventas/Procesos/Xmls/Clientes.xml");
                    requestMtPrecio.Method = WebRequestMethods.Ftp.UploadFile;
                    requestMtPrecio.Credentials = new NetworkCredential("activitymedellin@activitycolombia.com", "ts34Ng45Y64");
                    requestMtPrecio.UsePassive = false;
                    requestMtPrecio.UseBinary = true;
                    requestMtPrecio.KeepAlive = true;
                    // Defino el path del archivo
                    FileStream streamMtPrecio = File.OpenRead("D:\\ProcesosActivity\\XML\\Clientes.xml");
                    byte[] bufferMtPrecio = new byte[streamMtPrecio.Length];
                    streamMtPrecio.Read(bufferMtPrecio, 0, bufferMtPrecio.Length);
                    streamMtPrecio.Close();
                    Stream reqStreamMtPrecio = requestMtPrecio.GetRequestStream();
                    reqStreamMtPrecio.Write(bufferMtPrecio, 0, bufferMtPrecio.Length);
                    reqStreamMtPrecio.Flush();
                    reqStreamMtPrecio.Close();
                    Console.WriteLine("llego el xml Clientes");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }


                //Sube PRODUCTOS
                try
                {
                    FtpWebRequest requestMtPrecio = (FtpWebRequest)FtpWebRequest.Create("ftp://activitycolombia.com/mainwebsite_html/ventas/Procesos/Xmls/Productos.xml");
                    requestMtPrecio.Method = WebRequestMethods.Ftp.UploadFile;
                    requestMtPrecio.Credentials = new NetworkCredential("activitymedellin@activitycolombia.com", "ts34Ng45Y64");
                    requestMtPrecio.UsePassive = false;
                    requestMtPrecio.UseBinary = true;
                    requestMtPrecio.KeepAlive = true;
                    // Defino el path del archivo
                    FileStream streamMtPrecio = File.OpenRead("D:\\ProcesosActivity\\XML\\Productos.xml");
                    byte[] bufferMtPrecio = new byte[streamMtPrecio.Length];
                    streamMtPrecio.Read(bufferMtPrecio, 0, bufferMtPrecio.Length);
                    streamMtPrecio.Close();
                    Stream reqStreamMtPrecio = requestMtPrecio.GetRequestStream();
                    reqStreamMtPrecio.Write(bufferMtPrecio, 0, bufferMtPrecio.Length);
                    reqStreamMtPrecio.Flush();
                    reqStreamMtPrecio.Close();
                    Console.WriteLine("llego el xml Productos");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                
                // Leemos los XMLs y ejecutamos las consultas en la base de datos Activity
                try
                {
                    object obj1;
                    try
                    {

                        HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create("http://www.activitycolombia.com/ventas/lecturaXML.php");


                        ((HttpWebRequest)request1).UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; es-ES; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14";

                        HttpWebResponse response = (HttpWebResponse)request1.GetResponse();
                        StreamReader reader = new StreamReader(response.GetResponseStream());
                        char[] buffer1 = new char[10000];
                        int length = reader.Read(buffer1, 0, 10000);
                        string str = string.Empty;


                        while (length > 0)
                        {
                            string str2 = new string(buffer1, 0, length);
                            str = str + str2;
                            length = reader.Read(buffer1, 0, 10000);
                        }
                        reader.Close();
                        Console.WriteLine(str);

                    }
                    catch (Exception ex)
                    {
                        // MessageBox.Show("Error al Cargar: " + ex.Message.ToString());
                        obj1 = "NO";
                    }

                }
                catch (Exception ex)
                {
                    // MessageBox.Show("Error al Enviar Por: " + ex.Message.ToString());
                }
                
                // Enviar pedidos
                // Aqui importo desde Activity para Saint
                try
                {
                    HttpWebRequest fr;
                    string TGravable;
                    string TExento;
                    string contado;
                    string credito;
                    string esExento;
                    string codeHtml = string.Empty;
                    Uri targetUri = new Uri("http://www.activitycolombia.com/ventas/enviar_pedidos.php");
                    fr = (HttpWebRequest)HttpWebRequest.Create(targetUri);

                    StreamReader st = new StreamReader(fr.GetResponse().GetResponseStream());
                    codeHtml = st.ReadToEnd();
                    st.Close();
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(codeHtml);
                    //XmlWriterSettings settings = new XmlWriterSettings();
                    //settings.Indent = true;
                    //// Save the document to a file and auto-indent the output.
                    //XmlWriter writer = XmlWriter.Create("data.xml", settings);
                    //doc.Save(writer);
                    ////Console.WriteLine(doc);
                    ////Console.WriteLine(codeHtml);
                    XmlNodeList pedidos = doc.GetElementsByTagName("pedidos");
                    XmlNodeList lista = ((XmlElement)pedidos[0]).GetElementsByTagName("pedido");
                    int i = 0;
                    foreach (XmlElement nodo in lista)
                    {
                        XmlNodeList cliente = nodo.GetElementsByTagName("cedula_cliente");
                        XmlNodeList vendedor = nodo.GetElementsByTagName("cedula_usuario");
                        XmlNodeList esCredito = nodo.GetElementsByTagName("estado_credito");
                        XmlNodeList productos = nodo.GetElementsByTagName("producto");
                        XmlNodeList fechaPedido = nodo.GetElementsByTagName("fecha_pedido");
                        XmlNodeList contacto = nodo.GetElementsByTagName("contacto");
                        XmlNodeList direccion1 = nodo.GetElementsByTagName("direccion1");
                        XmlNodeList direccion2 = nodo.GetElementsByTagName("direccion2");
                        XmlNodeList telefono = nodo.GetElementsByTagName("telefono");
                        XmlNodeList identificacion = nodo.GetElementsByTagName("identificacion");
                        XmlNodeList valorPedido = nodo.GetElementsByTagName("valor_pedido");
                        XmlNodeList valorTotalDescuento = nodo.GetElementsByTagName("valor_total_descuento");
                        XmlNodeList valorTotalIVA = nodo.GetElementsByTagName("valor_total_iva");
                        XmlNodeList valorTotalBruto = nodo.GetElementsByTagName("valor_total_bruto");

                        if (valorTotalIVA[0].InnerText == "0") {
                            TGravable = "0";
                            TExento = valorTotalBruto[0].InnerText;
                        } else {
                            TGravable = valorTotalBruto[0].InnerText;
                            TExento = "0";
                        }

                        if (esCredito[0].InnerText == "0") {
                            contado = valorPedido[0].InnerText;
                            credito = "0";
                        } else {
                            contado = "0";
                            credito = valorPedido[0].InnerText;
                        }

                        string query_fact = "INSERT INTO [EnterpriseAdminDb].[dbo].[SAFACT] [CodSucu],[TipoFac],[CodEsta]," +
                                "[CodUsua],[EsCorrel],[Signo],[FechaT],[TipoTraE],[Factor],[MontoMEx],[CodClie],[CodVend]," +
                                "[CodUbic],[Descrip],[Direc1],[Direc2],[Telef],[ID3],[Monto],[MtoTax],[Fletes],[TGravable],"+
                                "[TExento],[CostoPrd],[CostoSrv],[DesctoP],[RetenIVA],[FechaI],[FechaE],[FechaV],[MtoTotal]," +
                                "[Contado],[Credito],[Cancell],[CancelE],[CancelC],[CancelT],[CancelG],[CancelP],[Cambio]," +
                                "[MtoExtra],[ValorPtos],[Descto1],[PctAnual],[MtoInt1],[Descto2],[PctManejo],[MtoInt2]," +
                                "[SaldoAct],[MtoPagos],[MtoNCredito],[MtoFinanc],[DetalChq],[TotalPrd],[TotalSrv],[Ngiros]," +
                                "[Nmeses],[MtoComiVta],[MtoComiCob],[MtoComiVtaD],[MtoComiCobD],[Notas1] VALUES (['00000']," +
                                "['E'],['SERVER'],['001'],[1],[1],['" + fechaPedido[0].InnerText + "'],[0],[1],[0],['" +
                                cliente[0].InnerText + "'],['" + vendedor[0].InnerText + "'],['01'],['" +
                                contacto[0].InnerText + "'],['" + direccion1[0].InnerText + "'],['" +
                                direccion2[0].InnerText + "'],['" + telefono[0].InnerText + "'],['" +
                                identificacion[0].InnerText + "'],[" + valorTotalBruto[0].InnerText + "],[" +
                                valorTotalIVA[0].InnerText + "],[0],[" + TGravable + "],[" + TExento + "]," +
                                "[0],[0],[0],[0],['" + fechaPedido[0].InnerText + "'],['" + fechaPedido[0].InnerText + "']," +
                                "['" + fechaPedido[0].InnerText + "'],[" + valorPedido[0].InnerText + "],[" + contado + "]," +
                                "[" + credito + "],[0],[" + valorPedido[0].InnerText + "],[0],[0],[0],[0],[0],[0],[0],[0],[0]," +
                                "[0],[0],[0],[0],[0],[0],[0],[0],[0],[" + valorTotalBruto[0].InnerText + "],[0],[0],[0],[0],[0],[0],[0],['Notas1'])";

                        int j = 1;
                        //db.Consulta("SELECT [NumeroD] FROM [EnterpriseAdminDb].[dbo].[SAFACT] WHERE [CodVend]='{0}'",cliente[0].InnerText);
                        string numeroD = "Consultamos";//db.Dr["NumeroD"].ToString();

                        foreach (XmlElement nodoProducto in productos)
                        {
                            XmlNodeList idProducto = nodoProducto.GetElementsByTagName("id_producto");
                            XmlNodeList cantidad = nodoProducto.GetElementsByTagName("cantidad");
                            XmlNodeList totalPedido = nodoProducto.GetElementsByTagName("total_pedido_articulo");
                            XmlNodeList valorUnitario = nodoProducto.GetElementsByTagName("valor_unitario");
                            XmlNodeList descripcion = nodoProducto.GetElementsByTagName("descripcion");
                            XmlNodeList costo = nodoProducto.GetElementsByTagName("costpro");
                            XmlNodeList valorDescuento = nodoProducto.GetElementsByTagName("valor_descuento");
                            XmlNodeList valorIva = nodoProducto.GetElementsByTagName("valor_iva");
                            XmlNodeList valorBruto = nodoProducto.GetElementsByTagName("valor_bruto");

                             if (valorIva[0].InnerText == "0") {
                                 esExento = "1";
                             } else {
                                 esExento = "0";
                             }

                            string query_item = "INSERT INTO [EnterpriseAdminDb].[dbo].[SAITEMFAC] [CodSucu],[TipoFac]," +
                                "[NumeroD],[NroLinea],[NroLineaC],[CodItem],[CodUbic],[CodVend],[Descrip1],[Refere]," +
                                "[Signo],[CantMayor],[Cantidad],[CantidadD],[CantidadO],[CantidadA],[CantidadU],[CantidadUA]," +
                                "[ExistAntU],[ExistAnt],[Tara],[TotalItem],[Costo],[Precio],[Descto],[NroUnicoL],[FechaE]," +
                                "[EsServ],[EsUnid],[EsFreeP],[EsPesa],[EsExento],[UsaServ],[DEsLote],[DESSeri],[DEsComp] " +
                                "VALUES (['00000'],['E'],[" + numeroD + "],[" + j + "],[0],['" + idProducto[0].InnerText + "'],['01'],['" +
                                cliente[0].InnerText + "'],['" + descripcion[0].InnerText + "'],['" + idProducto[0].InnerText +
                                "'],[1],[1],[" + cantidad[0].InnerText + "],[0],[0],[0],[0],[0],[0],['Definir'],[0],[" +
                                totalPedido[0].InnerText + "],[" + costo[0].InnerText + "],[" + valorUnitario[0].InnerText +
                                "],[0],[0],['" + fechaPedido[0].InnerText + "'],[0],[0],[0],[0],[" + esExento + "]," +
                                "[0],[0],[0],[0])";
                            Console.WriteLine(query_item);
                            j++;
                        }
                        //Console.WriteLine(query_fact);
                        i++;
                    }
                    //Console.WriteLine(i);
                }
                catch (Exception ex)
                {
                    // MessageBox.Show("Error al Enviar Por: " + ex.Message.ToString());
                }
                
                Console.WriteLine("Favor no cerrar la venta,Proceso Activity Technology");
                System.Threading.Thread.Sleep(900000);


            }
        } 
    }
}
